package com.hooper.sms.service.impl;

import com.hooper.common.util.SmsCodeGenerator;
import com.hooper.hosp.vo.msm.MsmVo;
import com.hooper.hospital.common.constant.HospConstant;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static com.hooper.hospital.common.constant.HospSetConstant.VALIDATE_PHONE_PATTERN;
import static com.hooper.hospital.common.result.ResultCodeEnum.PARAM_EMPTY;
import static com.hooper.hospital.common.result.ResultCodeEnum.PHONE_NOT_VALIDATE;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/10/04/0:04
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void sendCode(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        if (!Pattern.matches(VALIDATE_PHONE_PATTERN, phone)) {
            throw new HospitalException(PHONE_NOT_VALIDATE);
        }
        String code = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(code)) {
            code = SmsCodeGenerator.generate(6);
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
        }
        log.info("phone :{}\tcode:{}", phone, redisTemplate.opsForValue().get(phone));
    }

    public boolean sendCode(String phone,String code) {
        if (StringUtils.isAnyBlank(phone,code)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        if (!Pattern.matches(VALIDATE_PHONE_PATTERN, phone)) {
            throw new HospitalException(PHONE_NOT_VALIDATE);
        }
        String res = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(res)) {
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
        }
        log.info("phone :{}\tcode:{}", phone, redisTemplate.opsForValue().get(phone));
        return true;
    }

    @Override
    public boolean send(MsmVo msmVo) {
        if(!StringUtils.isEmpty(msmVo.getPhone())) {
            String code = (String)msmVo.getParam().get("code");
            return this.sendCode(msmVo.getPhone(),code);
        }
        return false;
    }
}
